package soar.basic;

import java.util.Date;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.text.SimpleDateFormat; 
import java.util.HashMap;

import net.sf.json.JSONObject;

public class Errlog
{
    private static String filename;
    private static InetSocketAddress addr;
    private static String dir;

    public static int init(String filename, String location)
    {//{{{
        if(filename == null || filename.isEmpty())
        {
            Errlog.filename=null;
            return 0;
        }

        Errlog.filename=new File(filename).getName();
        if(location == null || location.isEmpty())
            location=".";
        Errlog.addr=null;
        Errlog.dir=null;

        if(location.startsWith("//"))
        {
            String[] addr=location.substring("//".length()).split(":");
            InetSocketAddress sockaddr;
            try
            {
                sockaddr=new InetSocketAddress(addr[0],
                        Integer.parseInt(addr[1]));
            }
            catch(Exception e)
            {
                return -1;
            }
            Errlog.addr=sockaddr;
        }
        else
        {
            String dir;
            if(location.substring(0, 1).equals("/"))
                dir=location;
            else
                dir=(new File(".").getAbsolutePath())+"/"+location;
            File d=new File(dir);
            if(d.exists())
            {
                if(!d.isDirectory() ||
                        !d.canRead() || !d.canWrite() || !d.canExecute())
                    return -1;
            }
            else
            {
                if(!d.mkdir())
                    return -2;
            }
            Errlog.dir=dir;
        }

        return 0;
    }//}}}

    public static int add(String fmt, Object... args)
    {//{{{
        String msg=String.format(fmt, args);

        if(Errlog.filename == null)
        {
            Date date=new Date();
            String date_s=(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).
                format(date);
            System.out.println(date_s+" -- "+msg);
        }
        else if(Errlog.addr != null)
        {
            String buf;
            try
            {
                HashMap<String,String> m=new HashMap<String,String>();
                m.put("cmd", "LOG");
                m.put("filename", Errlog.filename);
                m.put("msg", msg);
                JSONObject j=JSONObject.fromObject(m);
                buf=j.toString();
                //System.out.println(buf);
            }
            catch(Exception e)
            {
                return -1;
            }

            DatagramSocket sock=null;
            try
            {
                byte[] b=buf.getBytes();
                sock=new DatagramSocket();
                DatagramPacket p=new DatagramPacket(b, 0, b.length,
                        Errlog.addr); 
                sock.send(p);
            }
            catch(Exception e)
            {   return -1;   }
            finally
            {
                try
                {   if(sock != null) sock.close();   }
                catch(Exception e)
                {   return -1;   }
            }
        }
        else if(Errlog.dir != null)
        {
            Date date=new Date();
            String date_s=(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).
                format(date);
            FileWriter file=null;
            try
            {
                file=new FileWriter(Errlog.dir+"/"+
                        Errlog.filename+".log."+
                        (new SimpleDateFormat("yyyyMMdd")).format(date),
                        true);
                file.write(date_s+" -- "+msg+"\n");
            }
            catch(IOException e)
            {   return -1;   }
            finally
            {
                try
                {   if(file != null) file.close();   }
                catch(IOException e)
                {   return -1;   }
            }
        }

        return 0;
    }//}}}
}
